package main

import (
	"compress/gzip"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"

	"golang.org/x/text/encoding/charmap"
	"golang.org/x/text/encoding/simplifiedchinese"
)

//getYoungestRev 获取svn仓库的最新修订号
func getYoungestRev(repoName string) (rev int, err error) {
	var (
		repoDir = filepath.Join(APP.RepositoriesDir, repoName)
		cmd     = exec.Command("cmd", "/c", APP.SvnlookBin+" youngest "+repoDir)
	)

	out, err := cmd.Output()
	if err != nil {
		return -1, err
	}

	rev, err = strconv.Atoi(strings.TrimSpace(string(out)))
	if err != nil {
		return -1, err
	}

	return rev, nil
}

// backupSvnRepo 使用svndump将仓库进行备份，并使用gzip压缩
func backupSvnRepo(repoName string) (dumpfile string, err error) {
	var (
		repoDir = filepath.Join(APP.RepositoriesDir, repoName)
		cmd     = exec.Command("cmd", "/c", APP.SvnadminBin+" dump --quiet "+repoDir)
	)

	dumpData, err := cmd.StdoutPipe()
	if err != nil {
		return "", err
	}
	defer dumpData.Close()

	if err := cmd.Start(); err != nil {
		return "", err
	}

	// 生成备份文件，并使用gzip压缩
	dumpfile = repoName + ".svndump.gz"
	gzf, err := os.Create(repoName + ".svndump.gz")
	if err != nil {
		return "", err
	}
	defer gzf.Close()

	gzw := gzip.NewWriter(gzf)
	defer gzw.Close()

	if name := toLatin1(repoName); name != "" {
		gzw.Header.Name = name + ".svndump"
	} else {
		gzw.Header.Name = "unknown.svndump"
	}

	if _, err := io.Copy(gzw, dumpData); err != nil {
		return "", err
	}

	return dumpfile, cmd.Wait()
}

func toLatin1(s string) string {
	gbk, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(s))
	if err != nil {
		return ""
	}

	latin1, err := charmap.ISO8859_1.NewDecoder().Bytes(gbk)
	if err != nil {
		return ""
	}

	return string(latin1)
}
